package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);


    @Override
    public Result queryById(Long id) throws InterruptedException {
        // Shop shop1 = queryWithPassThrough(id);
        Shop shop = queryWithMutex(id);
        if(shop != null){
            return Result.ok(shop);
        }
        return Result.fail("店铺不存在");
    }

    //逻辑删除解决缓存击穿
    public Shop queryWithLogicalExpire(Long id){
        //从redis中查询
        String json = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //redis中不存在，返回空
        if(StrUtil.isBlank(json)){
            return null;
        }
        //redis中存在
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        //将data对象转为shop对象
        JSONObject shopJson = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(shopJson, Shop.class);
        //判断缓存是否过期
        LocalDateTime expireTime = redisData.getExpireTime();
        if(LocalDateTime.now().isBefore(expireTime)){
            //缓存未过期,返回商铺信息
            return shop;
        }
        //缓存过期
        //尝试获取互斥锁
        boolean flag = tryLock(LOCK_SHOP_KEY + id);
        //未获取到锁,返回过期数据
        if(!flag){
            return shop;
        }
        //获取到锁
        //开启独立线程
        CACHE_REBUILD_EXECUTOR.submit(()->{
            try {
                saveShop2Redis(id,LOCK_SHOP_TTL);
            }catch (RuntimeException e){
                throw new RuntimeException(e);
            }
            finally {
                unlock(LOCK_SHOP_KEY + id);
            }
        });
        return shop;
    }

    //互斥锁解决缓存击穿
    public Shop queryWithMutex(Long id) throws InterruptedException {
        //1. 从redis中查询店铺信息
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //2.1 redis中存在，返回
        if(StrUtil.isNotBlank(shopJson)){
            return JSONUtil.toBean(shopJson,Shop.class);
        }
        //2.2 redis中不存在
        if(shopJson != null){
            return null;
        }

        Shop shop = null;
        try {
            //3 尝试获取互斥锁
            boolean flag = tryLock(LOCK_SHOP_KEY + id);
            //3.1 获取锁失败
            if(!flag){
                Thread.sleep(50);
                queryWithMutex(id);
            }
            //3.2 获取锁成功
            // 4 查询数据据库
            shop = getById(id);
            //若数据库中查到为空，将空值写入redis
            if(shop == null){
                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
                return null;
            }
            // 5 查询到将信息写入缓存，释放锁返回数据
            String jsonStr = JSONUtil.toJsonStr(shop);
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,jsonStr,CACHE_SHOP_TTL,TimeUnit.MINUTES);

        }catch (InterruptedException e){
            throw new RuntimeException(e);
        }finally {
            unlock(LOCK_SHOP_KEY+id);
        }
        return shop;
    }

    //缓存穿透
    public Shop queryWithPassThrough(Long id){
        //先从Redis中查，这里的常量值是固定的前缀 + 店铺id
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //如果不为空（查询到了），则转为Shop类型直接返回
        if (StrUtil.isNotBlank(shopJson)) {
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        //如果查询到的是空字符串，则说明是我们缓存的空数据
        if (shopJson != null) {
            return null;
        }
        //否则去数据库中查
        Shop shop = getById(id);
        //查不到返回一个错误信息或者返回空都可以，根据自己的需求来
        if (shop == null){
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        //查到了则转为json字符串
        String jsonStr = JSONUtil.toJsonStr(shop);
        //并存入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, jsonStr,CACHE_SHOP_TTL,TimeUnit.MINUTES);
        //最终把查询到的商户信息返回给前端
        return shop;
    }

    @Override
    @Transactional
    public Result updateBy(Shop shop) {
        //首先先判一下空
        if (shop.getId() == null){
            return Result.fail("店铺id不能为空！！");
        }
        //先修改数据库
        updateById(shop);
        //再删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY+shop.getId());
        return Result.ok();
    }
    public void saveShop2Redis(Long id, Long expirSeconds){
        Shop shop = getById(id);
        RedisData<Shop> redisData = new RedisData<>();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expirSeconds));
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
    }

    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }
}
